<?php

namespace app\openapi\controller;

use app\openapi\ApiBaseController;
use app\common\model\Order as OrderModel;
use app\openapi\validator\CreateOrderValidator;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Cache;

class Order extends ApiBaseController
{
    /**
     * 创建订单接口
     * @return \think\response\Json
     */
    public function index()
    {
        try{
            $params = $this->request->param();

            $result = $this->validate($params, CreateOrderValidator::class);
            if(true !== $result) {
                throw new ValidateException($result);
            }

            //创建订单
            $orderData = OrderModel::createOrder($params);

            //设置redis订单状态
            $redis = Cache::store('redis')->handler();
            $orderStateKey = implode(':', ['order_state', $orderData['order_num']]);
            $redis->set($orderStateKey, -1, ['nx', 'ex' => env('TRONSCAN.validateDataSecond')]);

            return $this->jsonSuccess('创建订单成功', [
                'order_num' => $orderData['order_num'],
                'goods_name' => base64_decode($orderData['goods_name']),
                'goods_price' => round($orderData['goods_price'] / 100, 2),
                'goods_amount' => $orderData['goods_amount'],
                'payment_type' => $orderData['payment_type'],
                'account' => $orderData['account'],
                'payment_price' => $orderData['payment_price']
            ]);
        }catch (Exception $e) {
            return $this->jsonError($e->getMessage());
        }catch (ValidateException $e) {
            return $this->jsonError($e->getMessage());
        }
    }
}